import json
import re

from django.contrib.auth import login, authenticate, logout
from django.http import JsonResponse
# Create your views here.
from django.views import View
from django_redis import get_redis_connection
from celery_tasks.email.tasks import send_verify_mail
from apps.users.models import User, Address
from apps.users.utils import generate_verify_token, check_verify_token
from utils.viewmixin import LoginMixin

"""
判断用户名是否重复
前端  ：用户 输入用户名后 ，失去了焦点 ，发送一个axios（ajax）请求
后端 :
    接受请求 ：接受用户名

    路由:get   /usernames/<username>/count/

    业务逻辑： 根据用户名 查询数据库 ，查询当前数量， 数量大于0说明已经注册过了
    响应 JSON格式
    {"count": 1, "code": "0", "errmsg": "OK"}

"""


class UsernameCountView(View):
    def get(self, request, username):
        # 步骤：
        #     1 接受用户名
        print(username)

        #     2 根据用户名查数据库
        count = User.objects.filter(username=username).count()

        #     3 返回响应
        return JsonResponse({"count": count, "code": "0", "errmsg": "OK"})


"""
注册
前端  ：用户 输入用户名，密码 确认密码 手机号 同意协议，点击注册按钮，发送axios请求
后端 :
    接受请求 ：接受JSON 数据

    路由:post '/register/'

    业务逻辑： 验证数据 保存到数据库 
    响应 JSON格式
    {"code": "0", "errmsg": "OK"}
    {"code": "400", "errmsg": "register fail"}

"""


class RegisterView(View):
    def post(self, request):
        # 步骤
        # 1接受请求
        body_byte = request.body
        # 获取json格式数据 转为字典
        body_dict = json.loads(body_byte)

        # 2获取数据
        username = body_dict.get("username")
        password = body_dict.get("password")
        password2 = body_dict.get("password2")
        mobile = body_dict.get("mobile")
        sms_code = body_dict.get("sms_code")
        allow = body_dict.get("allow")

        # 3验证数据
        # 3.1验证是否为空 有没有传
        # all 里传入列表 如果列表里 任一元素为flase或者空 结果就是false
        if not all([username, password, password2, mobile, sms_code, allow]):
            return JsonResponse({"code": "400", "errmsg": "register fail"})
        # 3.2正则验证
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return JsonResponse({"code": "400", "errmsg": "register fail"})

        # 短信验证码验证
        # 从redis里获取短信验证码
        redis_cli = get_redis_connection("code")
        redis_sms_code = redis_cli.get("sms_%s" % mobile)

        # 判断是否过期
        if redis_sms_code is None:
            return JsonResponse({'code': 400, 'errmsg': "短信验证码过期"})

        # 和用户发过来的验证码对比
        if redis_sms_code.decode().lower() != sms_code.lower():
            return JsonResponse({'code': 400, 'errmsg': "短信验证码输入错误"})

        # 4生成用户保存到数据库
        # 密码加密   数据保存可能不成功捕获异常
        # create_user 可以给密码加密
        try:
            user = User.objects.create_user(username=username, password=password, mobile=mobile)
        except Exception as e:
            print(e)
            return JsonResponse({'code': 400, 'errmsg': "用户保存失败，检查用户信息"})
        print("保存 用户到数据库成功")
        # 状态保持
        login(request, user)

        response = JsonResponse({"code": "0", "errmsg": "ok"})
        # 把用户名保存到cookie 方便在首页显示 有效期产品决定
        response.set_cookie('username', user.username, max_age=3600 * 24 * 5)

        # 5返回响应（json数据）
        return response


"""
注册
前端  ：用户 输入用户名，密码 勾选是否记住用户  点击登录按钮  发送axios请求
后端 :
    接受请求 ：接受JSON 数据 验证数据

    路由:post '/login/'

    业务逻辑： 验证数据  验证用户名和密码是否正确   状态保持
    响应 JSON格式
    {"code": "0", "errmsg": "OK"}
    {"code": "400", "errmsg": "login fail"}

"""


class LoginView(View):
    def post(self, request):
        # 1 接受数据 json
        body = request.body
        data_dict = json.loads(body)
        username = data_dict.get("username")
        password = data_dict.get("password")
        remembered = data_dict.get("remembered")

        # 2 验证数据 是否为空
        if not all([username, password, remembered]):
            return JsonResponse({"code": "400", "errmsg": "参数不全"})

        # 根据用户传入的username的值 判断是手机号还是用户名
        # 然后设置用户验证是使用手机号还是用户名
        if re.match('1[3-9]\d{9}', username):
            User.USERNAME_FIELD = 'mobile'
        else:
            User.USERNAME_FIELD = 'username'

        # 3 验证用户名和密码是否正确
        # 如果用户名密码正确 返回User对象 否则返回None
        user = authenticate(username=username, password=password)

        if user is None:
            return JsonResponse({"code": "400", "errmsg": "用户名或者密码错误"})

        # 4 状态保持  session
        login(request, user)

        # 5 判断是否记住登录 设置session的有效期
        if remembered:
            # 记住登录 默认2周
            request.session.set_expiry(None)

        else:
            # 不记住登录  浏览器关闭 session过期
            request.session.set_expiry(0)

        response = JsonResponse({"code": "0", "errmsg": "ok"})
        # 把用户名保存到cookie 方便在首页显示 有效期产品决定
        response.set_cookie('username', user.username, max_age=3600 * 24 * 5)

        # 6 返回响应
        return response


"""
注册
前端  ：用户 在首页点击退出 发送一个axios请求
后端 :

    路由:post 'http://www.meiduo.site:8000/logout/'

    业务逻辑： 清空session 和cookie 返回响应
    响应 JSON格式
    {"code": "0", "errmsg": "OK"}
    {"code": "400", "errmsg": "login fail"}

"""


class LogoutView(View):
    def delete(self, request):
        # 1调用logout清空状态保持的session

        logout(request)

        # 2删除cookie里的username
        response = JsonResponse({"code": "0", "errmsg": "ok"})
        response.delete_cookie('username')

        # 3返回响应

        return response


# LoginRequiredMixin验证用户是否登录
class UserInfoView(LoginMixin, View):
    def get(self, request):
        info_data = {
            "username": request.user.username,
            "mobile": request.user.mobile,
            "email": request.user.email,
            "email_active": request.user.email_active
        }

        return JsonResponse({
            'code': 0,
            'errmsg': '个人中心',
            "info_data": info_data
        })


'''
前端  点击设置 输入邮箱地址 点击保存 发送请求

后端
    接受请求  邮箱的地址
    逻辑  保存邮箱地址到用户信息里，发送一封激活邮件
    响应 json数据
    路由 /emails/  
    请求方式 put
'''


class SaveEmailView(View):
    def put(self, request):
        # 1.获取数据 邮箱地址
        json_body = request.body
        data_dict = json.loads(json_body)
        email = data_dict.get('email')
        # 校验数据
        if not email:
            return JsonResponse({'code': 400, 'errmsg': '邮箱地址不能为空'})
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return JsonResponse({"code": "400", "errmsg": "邮箱地址格式错误"})
            # 2 保存邮箱地址
        try:
            request.user.email = email
            request.user.save()
        except Exception as e:
            print(e)
            return JsonResponse({"code": "400", "errmsg": "邮箱保存失败"})

            # 3 发送邮件
        print("发送邮件")
        subject = "fa_zuan"

        recipient_list = [email]
        token = generate_verify_token(request.user.id)
        print("加密的id:", token)
        verify_url = "http://www.meiduo.site/send_verify_mail.html?%s" % token

        html_message = '<p>fa——zuan！</p>' \
                       '<p>fa使用美多商城。</p>' \
                       '<p>fa的邮箱为：%s 。请点击此链接激活您的邮箱：</p>' \
                       '<p><a href="%s">%s<a></p>' % (email, verify_url, verify_url)
        # 异步发送

        send_verify_mail.delay(subject=subject, html_message=html_message, recipient_list=recipient_list)
        print("发送成功,2222222222222222")
        # 4返回响应
        return JsonResponse({"code": "0", "errmsg": "ok"})


'''
前端发送
    用户点击邮箱里的激活链接 发送 /emails/verification/？token=xxx 请求
    
后端：
        接受请求 获取参数 验证
        逻辑 解密token得到user_id 根据user_id去数据库查询 数据 修改邮箱激活字段
        返回响应
        
    路由  put  /emails/verification/？token=xxx
'''


class EmailVerifyView(View):
    def put(self, request):
        # 1.获取参数
        token = request.GET.get('token')
        # 2.校验参数
        if token is None:
            return JsonResponse({'code': '400', 'errmsg': '缺少token'})
        # 3解密获取user_id
        user_id = check_verify_token(token)
        # 4判断user_id是否为空
        if user_id is None:
            return JsonResponse({"code": "400", "errmsg": "token错误"})
        try:
            # 5查询用户 数据
            user = User.objects.get(id=user_id)
        except Exception as e:
            print(e)
            return JsonResponse({"code": "400", "errmsg": "查询不到用户"})
        # 6修改用户邮箱激活字段为True
        user.email_active = True
        user.save()
        # 7返回响应
        return JsonResponse({'code': '0', 'errmsg': 'ok'})


class AddressCreateView(LoginMixin, View):
    def post(self, request):
        # 1.接收数据
        body = request.body
        data_dict = json.loads(body)
        # 2.获取参数
        receiver = data_dict.get("receiver")
        province_id = data_dict.get("province_id")
        city_id = data_dict.get("city_id")
        district_id = data_dict.get("district_id")
        place = data_dict.get("place")
        mobile = data_dict.get("mobile")
        tel = data_dict.get("tel")
        email = data_dict.get("email")
        # 验证参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({'code': '400', 'errmsg': '参数不全缺失'})
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse('参数mobile有误')
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return JsonResponse('参数tel有误')
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return JsonResponse('参数email有误')
        user = request.user
        try:
            address = Address.objects.create(
                user=user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email,
            )
        except Exception as e:
            print(e)
            return JsonResponse({'code': '400', 'errmsg': '保存数据失败'})
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }
        return JsonResponse({'code': 0, "errmsg": "ok", "address": address_dict})


class AddressView(LoginMixin, View):
    def get(self, request):
        # 1.获取用户对象
        user = request.user
        # 2.查询当前用户的所有地址信息
        addresses = Address.objects.filter(user=user, is_deleted=False)  # is_deleted=False过滤查询没有删除的
        # 3.转为字典数据
        addresses_list = []
        for address in addresses:
            addresses_list.append({
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email
            })
        # 4.返回
        return JsonResponse({'code': '0', 'errmsg': 'ok', 'addresses': addresses_list})


class AddressUpdata(LoginMixin, View):
    def put(self, request, address_id):
        """修改地址"""
        # 接收参数
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})
        try:
            Address.objects.filter(id=address_id).update(
                user=request.user,
                title=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )
        except Exception as e:
            print(e)
            return JsonResponse({'code': '400', 'errmsg': '修改地址信息失败！'})
        address = Address.objects.get(id=address_id)
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }
        return JsonResponse({'code': '0', 'errmsg': 'ok', 'addresses': address_dict})

    def delete(self, request, address_id):
        try:
            #         查询要删除的地址
            address = Address.objects.get(id=address_id)
            #         将地址逻辑删除设置为True
            address.is_deleted = True
            address.save()
        except Exception as e:
            return JsonResponse({'code': '400', 'errmsg': '删除失败'})
        return JsonResponse({'code': '0', 'errmsg': '删除成功'})


class DefaultAddress(LoginMixin, View):
    def put(self, request, address_id):
        try:
            # 接收参数,查询地址
            address = Address.objects.get(id=address_id)

            # 设置地址为默认地址
            request.user.default_address = address
            request.user.save()
        except Exception as e:
            print(e)
            return JsonResponse({'code': 400, 'errmsg': '设置默认地址失败'})

            # 响应设置默认地址结果
        return JsonResponse({'code': 0, 'errmsg': '设置默认地址成功'})


class UpdateTitleAddress(LoginMixin, View):
    def put(self, request, address_id):
        """设置地址标题"""
        # 接收参数：地址标题
        json_dict = json.loads(request.body.decode())
        title = json_dict.get('title')

        try:
            # 查询地址
            address = Address.objects.get(id=address_id)

            # 设置新的地址标题
            address.title = title
            address.save()
        except Exception as e:
            print(e)
            return JsonResponse({'code': 400, 'errmsg': '设置地址标题失败'})

        # 4.响应删除地址结果
        return JsonResponse({'code': 0, 'errmsg': '设置地址标题成功'})


class ChangePassword(LoginMixin, View):
    def put(self, request):
        body = request.body
        json_dict = json.loads(body)
        old_password = json_dict.get('old_password')
        new_password = json_dict.get('new_password')
        new_password2 = json_dict.get('new_password2')

        # 校验参数
        if not all([old_password, new_password, new_password2]):
            return JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})

        result = request.user.check_password(old_password)
        if not result:
            return JsonResponse({'code': 400, 'errmsg': '原始密码不正确'})

        if not re.match(r'^[0-9A-Za-z]{8,20}$', new_password):
            return JsonResponse({'code': 400, 'errmsg': '密码最少8位,最长20位'})

        if new_password != new_password2:
            return JsonResponse({'code': 400, 'errmsg': '两次输入密码不一致'})

        # 修改密码
        try:
            request.user.set_password(new_password)
            request.user.save()
        except Exception as e:

            return JsonResponse({'code': 400, 'errmsg': '修改密码失败'})

        # 清理状态保持信息
        logout(request)

        response = JsonResponse({'code': 0, 'errmsg': 'ok'})

        response.delete_cookie('username')

        # # 响应密码修改结果：重定向到登录界面
        return response
